﻿//Copyright (c) 2009, Offbeat Guides
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other materials 
//provided with the distribution.
//
//* Neither the name of Offbeat Guides nor the names of its contributors may be used to 
//endorse or promote products derived from this software without specific prior written 
//permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
//OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
//TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;

namespace Amazon.Services.S3
{
    internal class FileSystemHelper
    {
        #region Static Variables
        internal static readonly System.String MetadataFilename;
        internal static System.Text.RegularExpressions.Regex PathRegex;
        internal static System.Text.Encoding Encoding;
        #endregion

        #region Constructors and Finalizers
        static FileSystemHelper()
        {
            FileSystemHelper.MetadataFilename = "_dirMetadata";
            FileSystemHelper.Encoding = new UTF8Encoding();
            FileSystemHelper.PathRegex = new Regex(Properties.Resources.PathRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
        }
        #endregion

        #region Static Methods
        internal static Boolean IsDirectory(String path)
        {
            return path.EndsWith(FileSystemHelper.MetadataFilename);
        }

        internal static String ToDirectory(String path)
        {
            if (path.EndsWith(FileSystemHelper.MetadataFilename))
                return path;
            return FileSystemHelper.NormalizePath(String.Format("{0}/{1}", path.Trim('/'), FileSystemHelper.MetadataFilename));
        }

        internal static String NormalizePath(String path)
        {
            return path.Replace("\\", "/").Replace("//", "/").Trim('/');
        }

        internal static String[] GetObjectPaths(ServiceClient client, String bucket, String path)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            if (String.IsNullOrEmpty(bucket))
                throw new ArgumentNullException("bucket");
            if (path == null)
                throw new ArgumentNullException("path");

            List<String> paths = new List<String>();
            path = FileSystemHelper.NormalizePath(path);
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", bucket);
            parameters.Add("method", "GET");
            if (!String.IsNullOrEmpty(path))
                parameters.Add("prefix", FileSystemHelper.NormalizePath(path) + "/");

            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new System.IO.IOException("Unable to delete directory");

            // just some basic reader settings; mainly to prevents whitespace from being read
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            // tear is apart into the instances and return the list
            using (XmlReader reader = XmlTextReader.Create(new StringReader(response.Body), settings))
            {
                while (reader.ReadToFollowing("Key"))
                    paths.Add(reader.ReadElementString("Key"));
            }
            return paths.ToArray();
        }

        internal static String[] GetObjectPaths(ServiceClient client, String bucket, String path, Boolean includeFiles, Boolean includeDirs, Boolean recursive)
        {
            String[] allPaths = FileSystemHelper.GetObjectPaths(client, bucket, path);
            List<String> paths = new List<String>();

            // tear is apart into the instances and return the list
            Int32 level = path.Split(new Char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Length + 1;
            for (int i = 0; i < allPaths.Length; i++)
            {
                Boolean isDir = FileSystemHelper.IsDirectory(allPaths[i]);
                if (!recursive)
                {
                    Int32 pathLevel = allPaths[i].Split(new Char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Length;
                    if ((isDir && pathLevel != (level + 1)) || (!isDir && pathLevel != level))
                        continue;
                }

                if (isDir && includeDirs)
                    paths.Add(allPaths[i]);
                else if (!isDir && includeFiles)
                    paths.Add(allPaths[i]);
            }

            return paths.ToArray();
        }

        internal static void DeleteDirectory(ServiceClient client, String bucket, String path, Boolean recursive)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            if (String.IsNullOrEmpty(bucket))
                throw new ArgumentNullException("bucket");
            if (String.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            String[] paths = FileSystemHelper.GetObjectPaths(client, bucket, FileSystemHelper.NormalizePath(path));
            if (!recursive)
            {
                if (paths.Length > 1 || !paths[0].Equals(String.Format("{0}\\{1}", path, FileSystemHelper.MetadataFilename), StringComparison.OrdinalIgnoreCase))
                    throw new IOException("The directory contains one or more files or subdirectories");
            }

            try
            {
                String metadataFile = String.Empty;
                for (int i = 0; recursive && i < paths.Length; i++)
                {
                    String dirPath = paths[i].Replace(FileSystemHelper.MetadataFilename, String.Empty).TrimEnd('/');
                    if (dirPath.Equals(path, StringComparison.OrdinalIgnoreCase))
                        metadataFile = paths[i];
                    else
                        FileSystemHelper.DeleteFile(client, bucket, paths[i]);
                }

                //finally delete the directory metadata file if one exists(just in case)
                if (!String.IsNullOrEmpty(metadataFile))
                    FileSystemHelper.DeleteFile(client, bucket, metadataFile);
            }
            catch (Exception ex)
            {
                throw new AmazonException("Unable to delete directory.", ex);
            }
        }

        internal static void CreateFile(ServiceClient client, String bucket, String path)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            if (String.IsNullOrEmpty(bucket))
                throw new ArgumentNullException("bucket");
            if (String.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", bucket);
            parameters.Add("path", FileSystemHelper.NormalizePath(path));
            parameters.Add("method", "PUT");
            parameters.Add("content-type", "application/octet-stream");
            parameters.Add("x-amz-meta-hidden", "0");

            Response response = client.Invoke(parameters, new Byte[0]);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new System.IO.IOException("Unable to create file");
        }

        internal static void DeleteFile(ServiceClient client, String bucket, String path)
        {
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", bucket);
            parameters.Add("path", FileSystemHelper.NormalizePath(path));
            parameters.Add("method", "DELETE");

            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.NoContent)
                throw new System.IO.IOException("Unable to delete file");
        }

        internal static Boolean FileExists(ServiceClient client, String bucket, String path)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            if (String.IsNullOrEmpty(bucket))
                throw new ArgumentNullException("bucket");
            if (String.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            try
            {
                Dictionary<String, String> parameters = new Dictionary<String, String>();
                parameters.Add("bucket", bucket);
                parameters.Add("path", FileSystemHelper.NormalizePath(path));
                parameters.Add("method", "HEAD");

                Response response = client.Invoke(parameters, null);
                if (response.Status != System.Net.HttpStatusCode.OK)
                    throw new IOException("Unable to find file");

                return true;
            }
            catch (AmazonException ex)
            {
                if (ex.StatusCode != System.Net.HttpStatusCode.NotFound)
                    throw;
            }
            return false;
        }

        internal static void WriteFile(ServiceClient client, String bucket, String path, Byte[] contents)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            if (String.IsNullOrEmpty(bucket))
                throw new ArgumentNullException("bucket");
            if (String.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", bucket);
            parameters.Add("path", FileSystemHelper.NormalizePath(path));
            parameters.Add("method", "PUT");
            parameters.Add("content-type", "application/octet-stream");
            parameters.Add("x-amz-meta-hidden", "0");

            Response response = client.Invoke(parameters, contents);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new System.IO.IOException("Unable to create file");
        }

        internal static Byte[] ReadFile(ServiceClient client, String bucket, String path)
        {
            if (client == null)
                throw new ArgumentNullException("client");
            if (String.IsNullOrEmpty(bucket))
                throw new ArgumentNullException("bucket");
            if (String.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");

            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", bucket);
            parameters.Add("path", FileSystemHelper.NormalizePath(path));
            parameters.Add("method", "GET");

            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new System.IO.IOException("Unable to create file");

            return FileSystemHelper.Encoding.GetBytes(response.Body);
        }

        public static void SetAccessControl(ServiceClient client, String bucket, String path, AccessControlModes level)
        {
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", bucket);
            parameters.Add("path", String.Format("{0}?acl", FileSystemHelper.NormalizePath(path)));
            parameters.Add("method", "PUT");
            parameters.Add("x-amz-acl", level == AccessControlModes.Private ? "private" : "public-read");

            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new AmazonException("Unable to set access level", response.Status);
        }

        public static AccessControlModes GetAccessControl(ServiceClient client, String bucket, String path)
        {
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("bucket", bucket);
            parameters.Add("path", String.Format("{0}?acl", FileSystemHelper.NormalizePath(path)));
            parameters.Add("method", "GET");

            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new AmazonException("Unable to get access level", response.Status);

            // just some basic reader settings; mainly to prevents whitespace from being read
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            // tear is apart into the instances and return the list
            using (XmlReader reader = XmlTextReader.Create(new StringReader(response.Body), settings))
            {
                while (reader.ReadToFollowing("Grantee"))
                {
                    String type = reader.GetAttribute("xsi:type");
                    if (type.Equals("group", StringComparison.OrdinalIgnoreCase))
                    {
                        reader.ReadToFollowing("Permission");
                        String permission = reader.ReadElementString("Permission");
                        if (permission.Equals("read", StringComparison.OrdinalIgnoreCase) ||
                            permission.Equals("full_control", StringComparison.OrdinalIgnoreCase))
                            return AccessControlModes.Public;
                    }
                }
            }

            return AccessControlModes.Private;
        }
        #endregion
    }
}
